/**
 * There are <a href="https://github.com/thinkgem/jeesite">JeeSite</a> code generation
 */
package com.boxin.ims.modules.wechat.web;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.alibaba.fastjson.JSONObject;
import com.boxin.ims.modules.wechat.entity.LangType;
import com.boxin.ims.modules.wechat.entity.MemberMoney;
import com.boxin.ims.modules.wechat.entity.WeChat;
import com.boxin.ims.modules.wechat.entity.WechatMember;
import com.boxin.ims.modules.wechat.entity.WechatScene;
import com.boxin.ims.modules.wechat.service.MemberMoneyService;
import com.boxin.ims.modules.wechat.service.MemberScoreService;
import com.boxin.ims.modules.wechat.service.WeChatService;
import com.boxin.ims.modules.wechat.service.WechatDaoHelper;
import com.boxin.ims.modules.wechat.service.WechatMemberService;
import com.boxin.ims.modules.wechat.service.WechatSceneService;
import com.boxin.ims.modules.wechat.utils.AssertUtils;
import com.boxin.ims.modules.wechat.utils.ScoreUtils;
import com.boxin.ims.modules.wechat.utils.TokenUtils;
import com.boxin.ims.modules.wechat.utils.WechatInterfaceUtils;
import com.boxin.ims.modules.wechat.utils.WechatMenuUtils;
import com.google.common.collect.Maps;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.mapper.JsonMapper;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;
import com.zhixun.mobile.common.utils.StringUtils;

/**
 * 微信会员Controller
 * 
 * @author Jakemanse
 * @version 2013-09-08
 */
@Controller
@RequestMapping(value = Global.ADMIN_PATH + "/wechat/wechatMember")
public class WechatMemberController extends BaseController {

	@Autowired
	private WechatMemberService wechatMemberService;

	@Autowired
	private MemberScoreService memberScoreService;
	
	@Autowired
	private MemberMoneyService memberMoneyService;

	@Autowired
	private WeChatService weChatService;
	
	@Autowired
	private WechatSceneService wechatSceneService;

	@Autowired
	private WechatDaoHelper wechatDaoHelper;

	private final Logger logger = Logger
			.getLogger(WechatMemberController.class);

	@ModelAttribute
	public WechatMember get(@RequestParam(required = false) Long id) {
		if (id != null) {
			return wechatMemberService.get(id);
		} else {
			return new WechatMember();
		}
	}

	@RequiresPermissions("wechat:wechatMember:view")
	@RequestMapping(value = { "list", "" })
	public String list(WechatMember wechatMember, HttpServletRequest request,
			HttpServletResponse response, Model model) {
		
		String zhuce=request.getParameter("zhuce");
		if(StringUtils.isNotEmpty(zhuce)){
			wechatMember.setZhuce("1");
		}
		
		if(wechatMember.getUser()==null){
			wechatMember.setUser(null);
		}

		if (wechatMember.getStartTime() != null) {
			wechatMember.setCreateTime(wechatMember.getStartTime());
		} else {
			wechatMember.setCreateTime(null);

		}

		Page<WechatMember> page = wechatMemberService.find(new Page<WechatMember>(request, response), wechatMember);
		model.addAttribute("page", page);
		model.addAttribute("wechatMember", wechatMember);
		return "modules/wechat/wechatMemberList";
	}

	@RequiresPermissions("wechat:wechatMember:view")
	@RequestMapping(value = "form")
	public String form(WechatMember wechatMember, Model model) {
		model.addAttribute("wechatMember", wechatMember);
		return "modules/wechat/wechatMemberForm";
	}

	/**
	 * @author Jakemanse
	 * @time 2013-9-25 上午10:00:56
	 * @function <p>
	 *           微信会员积分充值
	 *           </p>
	 * @param wechatMember
	 * @param model
	 * @return
	 */
	@RequiresPermissions("wechat:wechatMember:view")
	@RequestMapping(value = "cform")
	public String chargeForm(WechatMember wechatMember, Model model) {
		model.addAttribute("wechatMember", wechatMember);
		return "modules/wechat/wechatMemberChargeScore";
	}
	
	
	/**
	 * 充值金额
	 *@author xiaoqian
	 * @param wechatMember
	 * @param model
	 * @return
	 * 2014-12-30下午2:45:47
	 */
	@ResponseBody
	@RequestMapping(value = "addMoney")
	public String addMoney(WechatMember wechatMember,HttpServletRequest request, Model model) {
		WechatMember member = wechatMemberService.get(wechatMember.getId());
		
		User user = UserUtils.getUser();
		
		
		try {
			String money = request.getParameter("addMoney");		//充值金客
			
			Integer moneyInt = (int)(Double.parseDouble(money)*100);
			
			wechatMember.setMoney(member.getMoney()+moneyInt);
			wechatMemberService.save(wechatMember);
			
			MemberMoney memberMoney = new MemberMoney();
			memberMoney.setWechatMember(member);
			memberMoney.setSerialNo(wechatDaoHelper.generateRechargeSerialNumber(user.getId()));
			memberMoney.setUser(user);
			memberMoney.setType(memberMoney.TYPE_RECHARGE);
			memberMoney.setManner("pcpay");
			memberMoney.setMoney(moneyInt);
			memberMoney.setRemarks("充值"+money+"元.");
			memberMoneyService.save(memberMoney);
			
		} catch (Exception e) {
			return "fail";
		}
		
		return "succeed";
	}
	

	/**
	 * @author Jakemanse
	 * @time 2013-9-25 上午9:55:39
	 * @function <p>
	 *           充值积分
	 *           </p>
	 * @param wechatMember
	 * @param request
	 * @param model
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("wechat:wechatMember:edit")
	@RequestMapping(value = "saveScore")
	public String saveScore(WechatMember wechatMember,
			HttpServletRequest request, Model model,
			RedirectAttributes redirectAttributes) {

		String chargeScore = request.getParameter("chargeScore");
		String tempScore = request.getParameter("tempScore");
		String type=request.getParameter("type");
		
		wechatMember = wechatMemberService.get(wechatMember.getId());
		if(wechatMember.getScore()==null)
		{
			wechatMember.setScore(0);
		}
		if (wechatMember != null) {
			//充值押金
			if("0".equals(type)){
				wechatMember.setUnusable((int)(Double.parseDouble(chargeScore)*1000));
				wechatMember.setScore(wechatMember.getScore()+wechatMember.getUnusable());
				ScoreUtils.addWechatMemberChargeScore(wechatMember,wechatMember.getUnusable(), "3", "充值押金");
			}
			//充值可用积分
			if("1".equals(type)){
				Integer resultScore=(int)(Double.parseDouble(chargeScore)*1000)+(int)(Double.parseDouble(tempScore)*1000);
				ScoreUtils.addScore(wechatMember, resultScore,"2","会员充值"+chargeScore+",赠送"+resultScore/1000d+"个信用积分");
				
			}

		}
		wechatMemberService.save(wechatMember);
		addMessage(redirectAttributes, "微信会员积分充值" + chargeScore + "分成功");
		return "redirect:" + Global.ADMIN_PATH + "/wechat/wechatMember/?repage";
	}

	@RequiresPermissions("wechat:wechatMember:edit")
	@RequestMapping(value = "save")
	public String save(WechatMember wechatMember, HttpServletRequest request,
			Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, wechatMember)) {
			return form(wechatMember, model);
		}

		wechatMemberService.save(wechatMember);
		addMessage(redirectAttributes, "保存微信会员'" + wechatMember.getName()
				+ "'成功");
		return "redirect:" + Global.ADMIN_PATH + "/wechat/wechatMember/?repage";
	}
	
	
	@RequestMapping(value = "sceneCode")
	public String sceneCode(  HttpServletRequest request,
			Model model, RedirectAttributes redirectAttributes) {
		User user = UserUtils.getUser();
		List<WechatMember> memberList = wechatMemberService.findAllMembersByUserId(user.getId());
		
		int count = 0;
		if(memberList != null){
			for(WechatMember wechatMember : memberList){
				if(StringUtils.isEmpty(wechatMember.getSceneTicket())){
					WechatScene wechatScene = new WechatScene();
					
					wechatScene.setUser(user);
					wechatScene.setType(WechatScene.SCENE_TYPE_MEMBER);		//会员推广码
					
					
					if(wechatScene.getSceneId()==null){
						Long sceneId=wechatSceneService.getSceneId();
						if(sceneId>100000){
							logger.error("场景值已经用完.");
						}
						wechatScene.setSceneId(sceneId);
					}
					wechatScene.setTicket(getTicket(wechatScene));
					
					wechatSceneService.save(wechatScene);
					
					logger.debug("生成会员的推广码成功...");
					
					//会员的推广码值
					wechatMember.setSceneTicket(wechatScene.getTicket());
					wechatMember.setSceneId(wechatScene.getSceneId()+"");
					
					wechatMemberService.save(wechatMember);
				}
				
				
			}
		}
		
		addMessage(redirectAttributes, "生成微信会员推广二维码'" 
				+count +"'个");
		return "redirect:" + Global.ADMIN_PATH + "/wechat/wechatMember/?repage";
	}

	@RequiresPermissions("wechat:wechatMember:edit")
	@RequestMapping(value = "delete")
	public String delete(Long id, RedirectAttributes redirectAttributes) {
		wechatMemberService.delete(id);
		addMessage(redirectAttributes, "删除微信会员成功");
		return "redirect:" + Global.ADMIN_PATH + "/wechat/wechatMember/?repage";
	}
	
	
	@RequiresPermissions("wechat:wechatMember:edit")
	@RequestMapping(value = "remove")
	public String remove(Long id, RedirectAttributes redirectAttributes) {
		wechatMemberService.remove(id);
		addMessage(redirectAttributes, "删除微信会员成功");
		return "redirect:" + Global.ADMIN_PATH + "/wechat/wechatMember/?repage";
	}

	@RequiresPermissions("wechat:wechatBusiness:view")
	@RequestMapping(value = "syncFromWechat")
	public String syncFromWechat(final User user, HttpServletRequest request,
			Model model) throws Exception {
		// System.out.println(accessToken);
		Runnable runner = new Runnable() {
			@Override
			public void run() {

				try {
					WeChat wechat = weChatService.getWeChatByUserId(user
							.getId());
					String accessToken = TokenUtils.getAPIToken(wechat);
					// wechatMemberService.updateWechatMemberFromWechat(accessToken,wechat);
					List<WechatMember> memberList = wechatMemberService
							.findAllMembersByUserId(user.getId());

					if (memberList != null && !memberList.isEmpty()) {
						for (WechatMember wechatMember : memberList) {
							try {
								
								WechatMember temp = WechatInterfaceUtils
										.getUserMessage(accessToken,
												wechatMember.getWechatId(),
												LangType.zh_CN);
								wechatMember.setNickname(temp.getNickname());
								wechatMember.setAge(temp.getAge());
								wechatMember.setProvince(temp.getProvince());
								wechatMember.setCity(temp.getCity());
								wechatMember.setCountry(temp.getCountry());
								wechatMember.setLanguage(temp.getLanguage());
								wechatMember.setHeadimgurl(temp.getHeadimgurl());
								wechatMember.setSubscribeTime(temp
										.getSubscribeTime());
								wechatMemberService.save(wechatMember);
								logger.debug("正在同步" + wechatMember.getName()
										+ "的高级接口信息...");
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
					}

					logger.debug("同步" + user.getName() + "帐号下的用户信息高级接口结束....");
				} catch (Exception e) {
					e.printStackTrace();
				}

			
				
			}
		};
		logger.debug("同步" + user.getName() + "帐号下的用户信息高级接口开始....");
		new Thread(runner).start();

		return "redirect:" + Global.ADMIN_PATH + "/sys/user/?repage";
	}
	@ResponseBody
	@RequestMapping(value = "syncFromWechatMember")
	public String syncFromWechatMember(HttpServletRequest request,
			Model model) throws Exception {
		String id = request.getParameter("id"); 
		Map<String,String> map=new HashMap<String,String>();
		if(StringUtils.isNotEmpty(id)){
			WeChat wechat = weChatService.getWeChatByUserId(2l);
			if(wechat!=null){
				String accessToken = TokenUtils.getAPIToken(wechat);
				WechatMember wechatMember = wechatMemberService
						.get(Long.parseLong(id));
				
				if (wechatMember != null ) {
						try {
							WechatMember temp = WechatInterfaceUtils
									.getUserMessage(accessToken,
											wechatMember.getWechatId(),
											LangType.zh_CN);
							if(StringUtils.isNotEmpty(temp.getNickname())){
								wechatMember.setNickname(temp.getNickname());
							}
							wechatMember.setAge(temp.getAge());
							wechatMember.setProvince(temp.getProvince());
							wechatMember.setCity(temp.getCity());
							wechatMember.setCountry(temp.getCountry());
							wechatMember.setLanguage(temp.getLanguage());
							wechatMember.setHeadimgurl(temp.getHeadimgurl());
							wechatMember.setSubscribeTime(temp
									.getSubscribeTime());
							wechatMemberService.save(wechatMember);
							
							map.put("msg", "success");
							map.put("message", "好了！");
							return JsonMapper.toJsonString(map);  
						} catch (Exception e) {
							e.printStackTrace();
						}
				}
			}
					
		}
		
		map.put("msg", "error");
		map.put("message", "出事了！");
		return JsonMapper.toJsonString(map);  
		
	}
	
	@RequiresPermissions("wechat:wechatBusiness:view")
	@RequestMapping(value = "reply")
	public String reply(Long id,HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		String replyContent=request.getParameter("replyContent");
		WechatMember wechatMember= wechatMemberService.get(id);
		Map<String,String> params = Maps.newHashMap();
		User user=UserUtils.getUser();
		WeChat weChat =weChatService.getWeChatByUserId(user.getId());
		Boolean flag=false;
		if(user.getInterfaceFlag()){
			String accessToken;
			try {
				accessToken =TokenUtils.getAPIToken(weChat);	//	 WechatMenuUtils.getAccessToken(weChat.getAppId(),weChat.getAppSecret());
				String textMessage=WechatInterfaceUtils.textMessageParams(wechatMember.getWechatId(), replyContent);
				System.out.println(textMessage);
				System.out.println(accessToken);
				String str=WechatInterfaceUtils.sendServiceMessage(textMessage, accessToken);
				if(str.equals("ok")){
					flag=true;
				}
			} catch (Exception e) {
				params.put("success", "false");
			}
		}
		if(flag){
			params.put("success", "true");
		}else{
			params.put("success", "false");
		}
		writeJson(request, response, params);
		return null;
	}

	/**
	 * 查询推荐会员
	 */
	@RequiresPermissions("wechat:wechatMember:view")
	@RequestMapping(value = "myRecommend")
	public String myRecommend(WechatMember wechatMember, Model model) {


		Map<String, String> map = new HashMap<String, String>();
		map.put("recommend_code", wechatMember.getRecommendCode());

		
		List  wechatMemberList = wechatMemberService.findMyRecommandMembers( wechatMember.getRecommendCode());

		model.addAttribute("memberCount", wechatMemberList == null ? 0 : wechatMemberList.size());
		model.addAttribute("wechatMemberList1", wechatMemberList);
		

		return "modules/wechat/myRecommendList";
	}

	/**
	 * 根据推荐码或手机号查询
	 */
	@RequiresPermissions("wechat:wechatMember:view")
	@RequestMapping(value = "recommend")
	public String recommend(WechatMember wechatMember, Model model) {

		List wechatMemberList = new ArrayList();

		Map<String, String> map = new HashMap<String, String>();

		String mobile = wechatMember.getMobile();

		String recommendCode = wechatMember.getRecommendCode();

		if (AssertUtils.isNullOrEmpty(mobile)
				&& AssertUtils.isNullOrEmpty(recommendCode)) {

		}// 参数都为空，跳回页面

		else {

			if (AssertUtils.notNullOrEmpty(recommendCode)
					&& AssertUtils.isNullOrEmpty(mobile)) {
				map.put("recommend_code", wechatMember.getRecommendCode());

				wechatMemberList = wechatDaoHelper.selectMyCommend(map);

				model.addAttribute("recommendMemberList", wechatMemberList);
			}

			else {

				map.put("recommend_code", recommendCode);
				map.put("mobile", mobile);

				String code = wechatDaoHelper.selectmemberBymobile(map);

				if (AssertUtils.notNullOrEmpty(code)) {
					map.clear();

					map.put("recommend_code", code);

					wechatMemberList = wechatDaoHelper.selectMyCommend(map);

					model.addAttribute("recommendMemberList", wechatMemberList);
				}

			}

		}

		return "modules/wechat/recommendList";
	}
	
	
	
	/**
	 * @author Jakemanse
	 * @time 2015-1-22  下午4:22:11
	 * @function <p> 生成渠道二维码的 Ticket </p>
	 * @param wechatScene
	 * @return
	 */
	public String getTicket(WechatScene wechatScene){
		User user = wechatScene.getUser();
		WeChat weChat= weChatService.getWeChatByUserId(user.getId());
		String qrcodeparams="";
		JSONObject object = null;
		wechatScene.setQrcodeType("QR_LIMIT_SCENE");
		try {
			String accessToken=TokenUtils.getAPIToken(weChat);
			
//			if(wechatScene.getQrcodeType().equals("QR_SCENE")){
//				qrcodeparams=WechatInterfaceUtils.createTemporaryQrCodeParams(wechatScene.getExpireSeconds().toString(), wechatScene.getSceneId().toString());
//			}else if(wechatScene.getQrcodeType().equals("QR_LIMIT_SCENE")){
//				qrcodeparams=WechatInterfaceUtils.createForeverQrCodeParams(wechatScene.getSceneId().toString());
//			}
			qrcodeparams=WechatInterfaceUtils.createForeverQrCodeParams(wechatScene.getSceneId().toString());
			object=WechatInterfaceUtils.createQrCode(qrcodeparams, accessToken);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return object.getString("ticket");
		
	}
	
	
	
	@RequestMapping(value = "updateMemberByAdmin")
	public String updateMemberByAdmin(@RequestParam String isAdmin,@RequestParam Long memberId, Model model) {
		wechatMemberService.updateMemberByIsAdmin(isAdmin, memberId);
		return "redirect:" + Global.ADMIN_PATH + "/wechat/wechatMember?repage";
	}
	
	@RequestMapping(value = "recommendMemberList")
	public String recommendMemberList(WechatMember wechatMember, HttpServletRequest request,HttpServletResponse response, Model model) {
		if(wechatMember.getUser()==null){
			wechatMember.setUser(null);
		}
		wechatMember.setCreateTime(null);
		String memberId  = request.getParameter("memberId");
		String isFind = request.getParameter("isFind");
		if("yes".equals(isFind)){
			Page<WechatMember> page = wechatMemberService.find(new Page<WechatMember>(request, response), wechatMember);
			model.addAttribute("page", page);			
		}
		model.addAttribute("isFind", isFind);
		model.addAttribute("memberId", memberId);
		model.addAttribute("wechatMember", wechatMember);
		return "modules/wechat/recommendMemberList";
	}
	
	@RequestMapping(value = "updateRecommendMember")
	public String updateRecommendMember(@RequestParam String parentCode,@RequestParam Long memberId, Model model){
		wechatMemberService.updateRecommendMemberById(parentCode,memberId);
		return null;
	}
	
	

}
